# -*- coding: utf-8 -*-
"""
  @Time    : 2023/3/1 11:33
  @Author  : 
  @email   : 
  @File    : tools.py
"""
from lib.docker_manage import DockerEngine
from flask import current_app
import requests
import json
import dns.resolver

res_403 = {
    "code": 403,
    "message": "Forbidden"
}

res_404 = {
    "code": 404,
    "message": "Not Found"
}

res_500 = {
    "code": 500,
    "message": "Server Internal Error"
}


def dict_merge(dict1, dict2):
    """
    对字典相同key的值进行合并成列表
    :param dict1: 合并后的字典
    :param dict2: 待合并的字典
    :return:
    """
    for key, value in dict2.items():
        dict1.setdefault(key, []).append(value)
    return dict1


def get_name_by_ip(base_url=None, request_url=None, container_ip=None):
    """
    通过IP查询容器信息
    :param base_url: 要连接的远程docker api地址
    :param request_url: 请求的url
    :param container_ip: 容器的IP地址
    :return:
    """
    res = {}
    container_name = ""
    docker_client = DockerEngine(base_url=base_url)
    for item in docker_client.network_list().values():
        ipaddress = item['IPv4Address'].split('/')[0]
        if container_ip == ipaddress:
            container_name = item['Name']
            res[container_name] = {}
            break
    if container_name:
        res[container_name]['Ip'] = container_ip
        if request_url:
            res[container_name]['Url'] = "%s/%s" % (
                request_url, container_name)
        return res
    else:
        current_app.logger.info(
            "from %s, %s query result is empty" %
            (base_url, container_ip))
        return None


def utc_to_beijing(utc_date: str) -> str:
    """
    UTC时间转北京时间
    :param utc_date: utc时间
    :return:
    """
    import datetime
    UTC_FORMAT = "%Y-%m-%dT%H:%M:%S"
    STR_FORMAT = "%Y-%m-%d %H:%M:%S"
    utc_date = utc_date.split('.')[0]
    utc_time = datetime.datetime.strptime(utc_date, UTC_FORMAT)
    local_time = utc_time + datetime.timedelta(hours=8)
    time_str = datetime.datetime.strftime(local_time, STR_FORMAT)
    return time_str


def byte_humanized_display(byte) -> str:
    """
    将字节转换成易于阅读的单位
    :param byte: 字节大小，int
    :return: 字符串
    """
    units = ["B", "KB", "MB", "GB", "TB", "PB"]
    size = 1024.0
    for i in range(len(units)):
        if (byte / size) < 1:
            return "%.2f%s" % (byte, units[i])
        byte = byte / size


def check_endpoint_status(endpoint: str) -> int:
    """
    检查端点是否可ping
    :param endpoint: 端点地址:端口
    :return: 状态码
    """
    url = "http://%s/_ping" % endpoint
    try:
        res = requests.get(url=url, timeout=1.5)
        return res.status_code
    except Exception as e:
        print(str(e))
        return 500

class SerializeData(object):
    def __init__(self, fp):
        self.fp = fp

    def dump_file(self, obj):
        with open(self.fp, 'w') as f:
            json.dump(obj, f)

    def load_file(self):
        with open(self.fp, 'r') as f:
            return json.load(f)

def resolve_with_specific_dns(domain, dns_server="10.10.10.10"):
    """
    指定dns服务器，解析域名返回IP地址列表
    :param domain: 要解析的域名
    :param dns_server: dns服务器地址
    :return:
    """
    try:
        # 创建解析器对象
        resolver = dns.resolver.Resolver()
        # 设置特定的 DNS 服务器
        resolver.nameservers = [dns_server]
        # 执行查询
        answer = resolver.resolve(domain, 'A')
        # 获取 IP 地址列表
        ip_addresses = [rdata.to_text() for rdata in answer]
        return ip_addresses
    except dns.resolver.NoAnswer:
        current_app.logger.error("No answer from DNS server.")
        return []
    except dns.resolver.NXDOMAIN:
        current_app.logger.error("%s does not exist." % domain)
        return []
    except Exception as e:
        current_app.logger.error(f"An error occurred: {e}")
        return []

# if __name__ == '__main__':
    # get_name_by_ip(base_url=current_app.config.get('BASE_URL_TEST')[0], container_ip="10.50.0.25")
    # utc_to_beijing('2023-03-02T09:02:01.865713586Z')
